package com.wang.log;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * @Author wangf
 * @Description 日志切面
 * @Date 2023/9/10 19:04
 */

@Aspect
@Slf4j
@Component
@ConditionalOnProperty(prefix = "log.aspect.enable", name = "log",havingValue = "true",matchIfMissing = true)
public class LogAspect {

    /**
     * 切点
     */
    @Pointcut("execution(* com.wang.*.controller.*Controller.*(..))||execution(* com.wang.*.service.*Service.*(..))")
    private void pointCut() {

    }

    @Around("pointCut()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] reqArgs = joinPoint.getArgs();
        String req = new Gson().toJson(reqArgs);
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String methodName=  methodSignature.getDeclaringType().getName()+"."+methodSignature.getName();
        log.info("请求方法：{}，请求参数：{}",methodName,req);
        Long startTime = System.currentTimeMillis();
        Object responsObj = joinPoint.proceed();
        String resp = new Gson().toJson(responsObj);
        Long endTime = System.currentTimeMillis();
        log.info("请求方法：{}，响应参数：{}，耗时：{}ms",methodName,resp,endTime-startTime);
    }
}
